#!/bin/sh

if [ ! -d "$1" ] || [ ! -d "$2" ] || [ ! -n "$3" ] || [ ! -n "$4" ]; then
cat<<HELP
Usage: ./hash_file.sh sourcePath hashPath hourago or date
Example: 
1 ./hash_file.sh /data/log /data/log/hash 20120113 06

HELP
    exit 1
fi

PWD="/opt/wanalytics/scripts"
TOOLS=`dirname $PWD`/Tools

# 判断$3，指定日期，例: 20120113 06
YEAR=${3:0:4}
MONTH=${3:4:2}
DAY=${3:6:2}
HOUR=$4

# 日志路径
#LOGS=$PWD/log/hash_file.log

# 数据源路径
SOURCE_PATH=$1

# hash file 路径
HASH_PATH=$2/$YEAR/$MONTH/$DAY

# 散列未匹配文件后缀名
NOMATCH_SUF=".nomatch"

# hash file
if [ ! -d "$HASH_PATH" ]; then
    mkdir -p $HASH_PATH
fi

IPAD_PID=`python -u $TOOLS/getPid.py 1 shell|sed 's/,/|/g'`
#ANDROID_PID=`python -u $TOOLS/getPid.py 3 shell|sed 's/,/|/g'`
ANDROID_PID="0bf8f9f8a3c904c0"

MIX_PID=$IPAD_PID"|"$ANDROID_PID

WAP_PID=`python -u $TOOLS/getPid.py 8 shell|sed 's/,/|/g'`
# wap 合作
WAPCL_PID=`python -u $TOOLS/getPid.py 21 shell|sed 's/,/|/g'`

# 18 内部合作
INNER_PID=`python -u $TOOLS/getPid.py 18 shell|sed 's/,/|/g'`
FILTER_PID=$INNER_PID"|"$WAP_PID"|"$WAPCL_PID

function ckPID()
{
    TMP=`echo $1|grep 'failed'`
    if [ -n "$TMP" ]; then
        echo $0" : "$1 $2 >> $LOGS
        exit 1
    fi
}

# check PID
ckPID $IPAD_PID
#ckPID $ANDROID_PID
ckPID $WAP_PID
ckPID $WAPCL_PID
ckPID $INNER_PID

# rsync 同步log 并排序
#if [ ! -s $SOURCE_PATH/access_$HOUR ];then
#    #rsync 
#fi

rm -rf $HASH_PATH/*/access_$HOUR*

# access_log
if [ -s $SOURCE_PATH/access_$HOUR ];then
    echo "cat $SOURCE_PATH/access_$HOUR | awk -f $PWD/access_log.awk -v output=$HASH_PATH -v mixpid=$MIX_PID -v fid=$FILTER_PID -v fname=access_$HOUR -v nomatch=$NOMATCH_SUF"
    cat $SOURCE_PATH/access_$HOUR | awk -f $PWD/access_log.awk -v output=$HASH_PATH -v mixpid=$MIX_PID -v fid=$FILTER_PID -v fname=access_$HOUR -v nomatch=$NOMATCH_SUF
else
    echo "File: "$SOURCE_PATH/access_$HOUR" is no exists"
fi

rm -rf $HASH_PATH/*/statis_$HOUR*

# stat_log
if [ -s $SOURCE_PATH/statis_$HOUR ];then
    echo "cat $SOURCE_PATH/statis_$HOUR | awk -f $PWD/statis_log.awk -v output=$HASH_PATH -v fname=statis_$HOUR"
    cat $SOURCE_PATH/statis_$HOUR | awk -f $PWD/statis_log.awk -v output=$HASH_PATH -v fid=$FILTER_PID -v fname=statis_$HOUR -v nomatch=$NOMATCH_SUF
else
    echo "File: "$SOURCE_PATH/statis_$HOUR" is no exists"
fi
